<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Agent;

class OperationLog
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (app()->environment()) {

            $user_id = Auth::id();
//            $user_username = Auth::user()->username;
            $user_username = 'yisheng';
//            $user_nickname = Auth::user()->nickname;
            $user_nickname = 'yisheng';
            $userString = join(' ', [$user_id, $user_username, $user_nickname]);
            //客户端ip
            $ip = $request->getClientIp();
            $uri = $request->path();
            $method = $request->method();
            //用户代理
            $userAgent = Agent::getUserAgent();
            $queryString = http_build_query($request->except(['password', 'sn', 'token']));

            $logMsg = join(' | ', [$userString, $method . ' ' . $uri . ' ' . $queryString, $userAgent, $ip]);

            //记录用户操作日志
            Log::channel('operation')->info($logMsg . PHP_EOL);
        }
        return $next($request);
    }
}
